package com.hoppinzq.service.util;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class SitemapGenerator {

    public static void main(String[] args) throws ParserConfigurationException, TransformerException {

        // 创建XML文档
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.newDocument();

        // 创建根元素
        Element urlset = doc.createElement("urlset");
        urlset.setAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
        doc.appendChild(urlset);

        // 添加URL元素
        addUrlElement(doc, urlset, "http://hoppin.cn", "daily", "1.0");
        addUrlElement(doc, urlset, "http://example.com/page1", "weekly", "0.8");
        addUrlElement(doc, urlset, "http://example.com/page2", "monthly", "0.6");

        // 保存文件
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(System.out);
        transformer.transform(source, result);
    }

    private static void addUrlElement(Document doc, Element urlset, String loc, String changefreq, String priority) {
        Element url = doc.createElement("url");
        urlset.appendChild(url);

        Element locElement = doc.createElement("loc");
        locElement.appendChild(doc.createTextNode(loc));
        url.appendChild(locElement);

        Element changefreqElement = doc.createElement("changefreq");
        changefreqElement.appendChild(doc.createTextNode(changefreq));
        url.appendChild(changefreqElement);

        Element priorityElement = doc.createElement("priority");
        priorityElement.appendChild(doc.createTextNode(priority));
        url.appendChild(priorityElement);
    }
}
